package com.design.composite.service.impl;

import com.design.composite.bean.ResponseResult;
import com.design.composite.entity.Material;
import com.design.composite.entity.Records;
import com.design.composite.repository.DictRepository;
import com.design.composite.repository.MaterialRepository;
import com.design.composite.repository.RecordsRepository;
import com.design.composite.service.IRecordsService;
import com.design.composite.utils.PicUtil;
import com.design.composite.web.param.GenerateInputParam;
import com.design.composite.web.param.GenerateMaterialParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


/**
 * @author liuyajun
 */
@Service
public class RecordsServiceImpl implements IRecordsService {

    @Autowired
    private RecordsRepository recordsRepository;
    @Autowired
    private MaterialRepository materialRepository;
    @Autowired
    private DictRepository dictRepository;
    @Autowired
    private PicUtil picUtil;

    @Override
    public ResponseResult preView(List<GenerateInputParam> paramList) {
        //先删除原有文件
        recordsRepository.deleteByCode("PREVIEW");
        String path = dictRepository.findByCode("PREVIEW").getPath();
        picUtil.delAllFile(path);
        List<GenerateMaterialParam> all = new ArrayList<>();
        paramList.forEach(c -> {
            List<Material> materials = materialRepository.findByClassifyId(c.getClassifyId());
            if (materials != null & materials.size() > 0) {
                Material material = materials.get(0);
                GenerateMaterialParam item = new GenerateMaterialParam();
                item.setClassifyId(c.getClassifyId());
                item.setFilePath(material.getFilePath());
                item.setSortNum(c.getSortNum());
                item.setX(c.getX());
                item.setY(c.getY());
                item.setMaterialName(material.getMaterialName());
                all.add(item);
            }
        });
        if (all != null && all.size() > 0) {
            Map<Integer, List<GenerateMaterialParam>> collect = all.stream().collect(Collectors.groupingBy(s -> s.getSortNum()));
            generate(collect, path, "PREVIEW");
            return ResponseResult.success(recordsRepository.findByCode("PREVIEW").get(0).getFileName());
        } else {
            return ResponseResult.fail("所选分类组合下无可用素材！");
        }
    }

    @Override
    public ResponseResult random(List<GenerateInputParam> paramList) {
        //先删除原有文件
        recordsRepository.deleteByCode("RANDOM");
        String path = dictRepository.findByCode("RANDOM").getPath();
        picUtil.delAllFile(path);
        List<GenerateMaterialParam> all = new ArrayList<>();
        paramList.forEach(c -> {
            List<Material> materials = materialRepository.findByClassifyId(c.getClassifyId());
            if (materials != null & materials.size() > 0) {
                materials.forEach(m -> {
                    GenerateMaterialParam item = new GenerateMaterialParam();
                    item.setClassifyId(c.getClassifyId());
                    item.setFilePath(m.getFilePath());
                    item.setSortNum(c.getSortNum());
                    item.setX(c.getX());
                    item.setY(c.getY());
                    item.setMaterialName(m.getMaterialName());
                    all.add(item);
                });
            }
        });
        if (all != null && all.size() > 0) {
            Map<Integer, List<GenerateMaterialParam>> collect = all.stream().collect(Collectors.groupingBy(s -> s.getSortNum()));
            generate(collect, path, "RANDOM");
            return ResponseResult.success(null);
        } else {
            return ResponseResult.fail("所选分类组合下无可用素材！");
        }
    }

    public void generate(Map<Integer, List<GenerateMaterialParam>> map, String savePath, String code) {
        Map<Integer, List<GenerateMaterialParam>> sortedMap = picUtil.sortMapByKey(map);
        int i = 1;
        sortedMap.get(i).forEach(s -> {
            try {
                List<GenerateMaterialParam> compositeList = new ArrayList<>();
                compositeList.add(s);
                picUtil.generateBufferImages(map, i + 1, compositeList, savePath, code);
            } catch (IOException e) {
                e.printStackTrace();
            }

        });

    }

    @Override
    public ResponseResult randomResults() {
        return ResponseResult.success(recordsRepository.findByCode("RANDOM"));
    }

    @Override
    public void randomTransform(String toPath) throws IOException {
        List<Records> randoms = recordsRepository.findByCode("RANDOM");
        for (Records record : randoms) {
            String filePath = record.getFilePath();
            File file = new File(filePath);
            String newFilePath = toPath + record.getFileName();
            File toFile = new File(newFilePath);
            if (toFile.exists()){
                toFile = new File(toPath + new Timestamp(System.currentTimeMillis()).getTime() + record.getFileName());
            }
            Files.copy(file.toPath(), toFile.toPath());
        }
    }
}

